import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth'
import Layout from './views/layout/Layout' // get token from cookie

NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const res = await store.dispatch('GetInfo')
          const { roles } = res.result

          // generate accessible routes map based on roles
          global.antRouter = await store.dispatch('permission/generateRoutes', roles)

          // dynamically add accessible routes

          router.addRoutes(global.antRouter)
          router.addRoutes([{ path: '*', meta: { go: true }, redirect: '/404', hidden: true }])
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('FedLogOut')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (to.meta.go) {
      if (global.antRouter === undefined) {
        global.antRouter = [
          { path: '/login', meta: { go: true }, component: () => import('@/views/login/index'), hidden: true },
          { path: '/404', meta: { go: true }, component: () => import('@/views/404'), hidden: true },

          // 首页
          {
            path: '/',
            component: Layout,
            redirect: '/index',
            name: '首页',
            meta: { go: true },
            children: [{
              path: 'index',
              component: () => import('@/views/home/index'),
              meta: { title: '首页', go: true }
            }]
          },
          // 博客
          {
            path: '/blog',
            component: Layout,
            meta: { go: true },
            children: [{
              path: '',
              name: '博客',
              component: () => import('@/views/blog/index'),
              meta: { title: '博客', go: true }
            }]
          },
          // 试题
          {
            path: '/problem',
            component: Layout,
            meta: { go: true },
            children: [{
              path: '',
              name: '试题',
              component: () => import('@/views/problem/index'),
              meta: { title: '试题', go: true }
            }]
          }
        ]
      }
      next()
      NProgress.done()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
